package com.dgsrz.demo.primitive;

import javax.microedition.khronos.opengles.GL10;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.FloatBuffer;
import java.util.Arrays;

/**
 * Created by dgsrz on 15/7/3.
 */
public class Rectangle extends PrimitiveBase {

    private final int PRIM_VERTEX_NUM = 4;

    private FloatBuffer mVertexBuffer;
    private FloatBuffer mTexBuffer;

    private final float PRIM_VERTEX[] = {
            0, 0, 0,
            1f, 0, 0,
            0, 1f, 0,
            1f, 1f, 0,
    };

    private final float PRIM_TEX_COORDS[] = {
            0, 0,
            1f, 0,
            0, 1f,
            1f, 1f,
    };

    private int mTexCoordsStartRow = 0;

    public Rectangle(final GL10 gl, final int width, final int height) {
        super(gl);

        PRIM_VERTEX[3] = PRIM_VERTEX[9] = width;
        PRIM_VERTEX[7] = PRIM_VERTEX[10] = height;

        ByteBuffer vbb = ByteBuffer.allocateDirect(PRIM_VERTEX_NUM * 3 * 4);
        vbb.order(ByteOrder.nativeOrder());
        mVertexBuffer = vbb.asFloatBuffer();
        mVertexBuffer.put(PRIM_VERTEX);
        mVertexBuffer.position(0);

        ByteBuffer tbb = ByteBuffer.allocateDirect(PRIM_VERTEX_NUM * 2 * 4);
        tbb.order(ByteOrder.nativeOrder());
        mTexBuffer = tbb.asFloatBuffer();
        mTexBuffer.put(PRIM_TEX_COORDS);
        mTexBuffer.position(0);
    }

    @Override
    public void drawPrimitives() {
        final GL10 gl = getGLStateManager();

        gl.glFrontFace(GL10.GL_CCW);
        gl.glVertexPointer(3, GL10.GL_FLOAT, 0, mVertexBuffer);
        gl.glTexCoordPointer(2, GL10.GL_FLOAT, 0, mTexBuffer);
        gl.glDrawArrays(GL10.GL_TRIANGLE_STRIP, 0, PRIM_VERTEX_NUM);
    }
}
